import { throttle, objectEqual } from '@/lib/util'

// 节流重定向
export const throttleRedirectLogin = throttle((data) => {
  const loginUrl = data?.result?.loginUrl
  if (loginUrl) {
    window.location.href = loginUrl
  }
}, 500)
// 判断返回是否成功
export const isSuccess = (res, options) => {
  const code = res.data.code === undefined ? res.data.result : res.data.code
  const successCode = options.successCode !== undefined ? options.successCode : 200
  return (code === successCode || options.noSuccessCode)
}

// application/octet-stream文件下载获取文件名
export const getFileNameFormHeader = (disposition) => {
  let result = null
  const reg = /filename=.*/ig
  if (disposition && reg.test(disposition)) {
    result = disposition.match(reg)
    return decodeURI(result[0].split('=')[1])
  } else {
    return null
  }
}
// 下载流
export const downloadByStream = (stream, filename) => {
  const blob = new Blob([stream])
  const eLink = document.createElement('a')
  eLink.download = filename
  eLink.style.display = 'none'
  eLink.href = URL.createObjectURL(blob)
  document.body.appendChild(eLink)
  eLink.click()
  URL.revokeObjectURL(eLink.href)
  document.body.removeChild(eLink)
}
// 对比get请求的请求地址及query
export const equalRequest = (requestSignA, requestSignB) => {
  const { url: urlA, query: queryA } = requestSignA
  const { url: urlB, query: queryB } = requestSignB

  if (urlA !== urlB) return false
  if (objectEqual(queryA, queryB)) return false

  return true
}
